// pages/sourceindex/index.js
import baseRequest from '../../utils/base-request';
import config from '../../config/index';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    pageIndex: 1,
    nextLoading: false,
    nextLoadingText: '',
    searchValue: '',
    bannerCode: config.softSearchBannerAdCode
    
  },
  handleBackClick(){
    wx.navigateBack();
  },
  handleClearSearch(){
    this.setData({
      searchValue:''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const key = options['key'] || '';
    this.setData({
      searchValue:key
    })
    this.loadData(1,key);
    this.initAdShow();
  },
  loadData(pageNum,key) {
    this.setData({
      nextLoading: true
    })
    wx.showLoading({
      title: '列表加载中...',
    })
    baseRequest('/_api/source-api/get-list', {
      currentIndex: pageNum,
      nameStr: key
    }).then(res => {
      this.setData({
        list: pageNum<=1 ? (res || []) : this.data.list.concat(res || []),
        pageIndex: res.length ? pageNum : pageNum - 1,
        nextLoading: false,
        nextLoadingText: res.length<=10 ? '' :  '正在加载下一页'
      })
      wx.hideLoading();
    })
  },
  // 触底加载
  onReachBottom: function () {
    if (!this.data.nextLoading) {
      this.loadData(this.data.pageIndex + 1, this.data.searchValue)
    }
  },
  onSearchTextChnage(event) {
    const val = event.detail.value || '';
    this.setData({
      searchValue: val
    })
  },
  handleSearchClick() {
    const key = this.data.searchValue.trim();
    if (!key) {
      wx.showToast({
        icon:'error',
        title: '请输入软件关键字',
        duration: 1000
      })
      return;
    }
    this.loadData(1,key);
  },
  handleItemClick(event) {
    const itemId = event.currentTarget.dataset.sid;
    wx.navigateTo({
      url: '/pages/sourcedet/index?itemid=' + itemId,
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 插屏广告
  initAdShow() {
    // 在页面中定义插屏广告
    let interstitialAd = null

    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: config.searchPageInsertAd
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }
    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },
})